﻿using System;
using System.Web.Mvc;
using GabageFactory.Models;
using GabageFactory.Utiliy.Crypt;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace GabageFactory.Controllers
{
    [Authorize]
    public class EventController : BaseController
    {
        private EventReposity eventReposity;

        private FactoryReposity factoryReposity;

        private UserReposity userReposity;

        private string[] types = { "", "输浆管","回水管","泵房","虹吸管","斜槽","截洪沟","初期堤","堆积坝","HDPE膜","山坡","底部导渗","堆体导渗","排洪设施","机械","其他" };

        private string[] priorities = { "", "非常紧急", "紧急", "一般紧急", "普通", "无限制" };

        public EventController()
        {
            eventReposity = new EventReposity();
            factoryReposity = new FactoryReposity();
            userReposity = new UserReposity();
        }

        public ActionResult List(int status = 0, int PageNo = 0)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Manager);
            roles.Add(RoleEnum.Expert);
            roles.Add(RoleEnum.Analyzer);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            long factoryId = 0;
            if (user.RoleId != (int)RoleEnum.Analyzer && user.RoleId != (int)RoleEnum.Expert)
            {
                factoryId = user.FactoryId;
            }

            Pagination pagination = new Pagination();
            pagination.PageNo = PageNo;
            IEnumerable<EventRecordDetail> eventRecords = eventReposity.ListEventRecords(factoryId, status, pagination);

            ViewData["eventRecords"] = eventRecords;
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;
            ViewData["status"] = status;
            ViewData["currentPage"] = pagination.PageNo;
            ViewData["totalPage"] = pagination.TotalPage;

            return View();
        }

        public ActionResult OnTrack()
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Manager);
            roles.Add(RoleEnum.Expert);
            roles.Add(RoleEnum.Analyzer);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            long factoryId = 0;
            if (user.RoleId != (int)RoleEnum.Analyzer && user.RoleId != (int)RoleEnum.Expert)
            {
                factoryId = user.FactoryId;
            }
            IEnumerable<EventRecordDetail> eventRecords = eventReposity.ListOnTrackEventRecords(factoryId);

            ViewData["eventRecords"] = eventRecords;
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;

            return View();
        }

        public ActionResult Search(EventSearch es)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Manager);
            roles.Add(RoleEnum.Expert);
            roles.Add(RoleEnum.Analyzer);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;

            es = es ?? new EventSearch();
            bool showFactory = true;
            if (user.RoleId != (int)RoleEnum.Analyzer && user.RoleId != (int)RoleEnum.Expert)
            {
                es.FactoryID = user.FactoryId;
                showFactory = false;
            }
            ShowUserList(es.FactoryID, RoleEnum.Recorder, es.RecorderId);

            List<SelectListItem> users = new List<SelectListItem>();

            foreach (User u in userReposity.QueryUsers(null, (int)RoleEnum.Expert, 0))
            {
                bool selected = false;
                if (es.RecorderId == u.Id)
                {
                    selected = true;
                }
                users.Add(new SelectListItem { Text = u.RealName + "(" + u.Name + ")", Value = u.Id.ToString(), Selected = selected });
            }

            ((List<SelectListItem>)ViewData["users"]).AddRange(users);

            ViewData["showFactory"] = showFactory;

            int stackType = 0, stackId = 0;
            ParseSid(es.stackId, ref stackId, ref stackType);
            es.Stack_Id = stackId;
            es.StackType = stackType;
            ShowFactoryList(es.FactoryID);
            ShowStackAndTailingoind(es.FactoryID, 0, stackId, stackType);

            IEnumerable<EventRecordDetail> eventRecords = eventReposity.SearchEventRecords(es);

            ViewData["eventRecords"] = eventRecords;
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;

            return View(es);
        }

        public ActionResult ReTrack(long eventId)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Auditor);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            EventRecord er = eventReposity.GetEventRecordById(eventId);
            IEnumerable<EventDailyRecord> dailyRecords = eventReposity.ListEventDailyRecords(eventId);
            EventDailyRecord dailyRecord = dailyRecords.Where(item => item.Status == 2).First();
            if (dailyRecord != null)
            {
                dailyRecord.Status = 1;
                eventReposity.UpdateEventDailyRecord(dailyRecord);
            }
            er.Status = 0;
            eventReposity.UpdateEventRecord(er);

            return RedirectToAction("List", new { status = 1 });
        }

        public ActionResult Track(long eventId)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Manager);
            roles.Add(RoleEnum.Expert);
            roles.Add(RoleEnum.Analyzer);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            EventRecord er = eventReposity.GetEventRecordById(eventId);
            IEnumerable<EventDailyRecord> eventDailyRecords = eventReposity.ListEventDailyRecords(eventId);

            Dictionary<long, string> recorders = new Dictionary<long, string>();
            foreach (EventDailyRecord record in eventDailyRecords)
            {
                User u = userReposity.GetUserById(record.RecorderId);
                if (u != null && !recorders.Keys.Contains(u.Id))
                {
                    recorders.Add(u.Id, u.RealName + "(" + u.Name + ")");
                }
            }

            ViewData["recorders"] = recorders;

            if ((er.Status == 0 && user.RoleId == (int)RoleEnum.Recorder) && !(eventDailyRecords.Where(item => item.OccurredDate.Date == DateTime.Now.Date).Count() > 0))
            {
                EventDailyRecord e = new EventDailyRecord();
                e.EventId = eventId;
                e.CreatedDate = DateTime.Now;
                e.OccurredDate = DateTime.Now;
                e.Status = 0;
                e.PicNum = 0;
                List<EventDailyRecord> records = eventDailyRecords.ToList();
                records.Add(e);
                eventDailyRecords = records;
            }
            ViewData["eventRecord"] = er;
            ViewData["eventDailyRecords"] = eventDailyRecords;

            return View();
        }

        public ActionResult EndEvent(long eventId)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Auditor);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;

            
            EventRecord e = eventReposity.GetEventRecordById(eventId);
            EventRecordDetail detail = eventReposity.GetEventDetail(e);
            EventDailyRecord ed = new EventDailyRecord();
            ed.RecorderId = user.Id;
            ed.CreatedDate = DateTime.Now;
            ed.OccurredDate = DateTime.Now;
            ed.EventId = eventId;
            ed.Status = 3;

            ViewData["dailyRecord"] = ed;

            return View(detail);
        }

        [HttpPost]
        public ActionResult EndEvent(FormCollection form)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Auditor);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;


            string eventDesc = form.Get("EventDesc");
            int eventId = parseInt(form.Get("eventId"));

            EventDailyRecord ed = new EventDailyRecord();
            ed.CreatedDate = DateTime.Now;
            ed.EventId = eventId;
            ed.OccurredDate = DateTime.Now;
            ed.RecorderId = GetCurrentUser().Id;
            ed.Description = eventDesc;
            ed.PicNum = 0;
            ed.Progress = 100;
            ed.Status = 3;


            eventReposity.CreateEventDailyRecord(ed);

            EventRecord e = eventReposity.GetEventRecordById(ed.EventId);
            EventRecordDetail detail = eventReposity.GetEventDetail(e);
            e.Progress = 100;
            e.Status = 2;
            e.EndDate = DateTime.Now;
            eventReposity.UpdateEventRecord(e);

            ViewData["dailyRecord"] = ed;

            return RedirectToAction("Track", new { eventId = ed.EventId });
        }

        public ActionResult Delete(long eventId)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            EventRecord e = eventReposity.GetEventRecordById(eventId);
            try
            {
                string stackFolder = e.FactoryID.ToString("00") + e.Stack_Id.ToString("00") + (e.StackType == 0 ? "dc" : "wk");
                string dateFolder = e.OccurredDate.ToString("yyyyMMdd") + "_" + e.Id.ToString("00");
                string filePath = "~/Upload/Events/" + stackFolder + "/" + dateFolder + "/";
                filePath = Server.MapPath(filePath);
                if (Directory.Exists(filePath))
                {
                    Directory.Delete(filePath, true);
                }
            }
            catch
            {
                //empty
            }

            eventReposity.DeleteEventRecord(eventId);
            eventReposity.DeleteEventDailyRecordByEventId(eventId);

            return RedirectToAction("List", new { status = 0});
        }

        public ActionResult Detail(long eventId, long dailyId)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Manager);
            roles.Add(RoleEnum.Analyzer);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;

            EventRecord e = eventReposity.GetEventRecordById(eventId);
            IEnumerable<EventDailyRecord> dailyRecords = eventReposity.ListEventDailyRecords(eventId);
            EventDailyRecord firstRecord = dailyRecords.First();
            EventDailyRecord lastRecord = dailyRecords.Last();
            List<EventDailyRecord> recordList = dailyRecords.ToList();
            EventDailyRecord dailyRecord = null;
            long preDailyId = 0;
            long nextDailyId = 0;
            for (int i = 0; i < recordList.Count; i++)
            {
                if (recordList[i].Id == dailyId)
                {
                    dailyRecord = recordList[i];
                    if (i > 0)
                    {
                        preDailyId = recordList[i - 1].Id;
                    }
                    if (i < (recordList.Count - 1) && recordList[i + 1].Status != 3)
                    {
                        nextDailyId = recordList[i + 1].Id;
                    }
                    break;
                }
            }

            EventRecordDetail detail = eventReposity.GetEventDetail(e);


            ViewData["recorder"] = userReposity.GetUserById(dailyRecord.RecorderId);
            ViewData["firstRecord"] = firstRecord;
            ViewData["lastRecord"] = lastRecord;
            ViewData["dailyRecord"] = dailyRecord;
            ViewData["preDailyId"] = preDailyId;
            ViewData["nextDailyId"] = nextDailyId;

            return View(detail);
        }

        public ActionResult EditDailyRecord(long id)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;

            EventDailyRecord ed = eventReposity.GetEventDailyRecordById(id);
            EventRecord e = eventReposity.GetEventRecordById(ed.EventId);
            EventRecordDetail detail = eventReposity.GetEventDetail(e);

            ViewData["dailyRecord"] = ed;

            return View(detail);
        }

        [HttpPost]
        public ActionResult EditDailyRecord(FormCollection form)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;


            string eventDesc = form.Get("EventDesc");
            int progress = parseInt(form.Get("progress"));
            int status = parseInt(form.Get("status"));
            int id = parseInt(form.Get("id"));
            int eventId = parseInt(form.Get("eventId"));
            DateTime occurredDate = DateTime.Parse(form.Get("occurredDate"));

            EventDailyRecord ed = eventReposity.GetEventDailyRecordById(id);
            EventRecord e = eventReposity.GetEventRecordById(ed.EventId);
            ed.OccurredDate = occurredDate;
            ed.RecorderId = GetCurrentUser().Id;
            ed.Description = eventDesc;
            ed.Progress = progress;
            ed.Status = status + 1;

            StoreImages(form, e, ed);
            eventReposity.UpdateEventDailyRecord(ed);
            EventRecordDetail detail = eventReposity.GetEventDetail(e);
            e.Progress = progress;
            if (status > 0)
            {
                e.Status = status;
            }
            eventReposity.UpdateEventRecord(e);

            ViewData["dailyRecord"] = ed;

            return RedirectToAction("Track", new { eventId = ed.EventId });
        }

        public ActionResult DeleteDailyRecord(long id)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }

            EventDailyRecord ed = eventReposity.GetEventDailyRecordById(id);
            long eventId = ed.EventId;
            DeleteFile(ed.Pic1);
            DeleteFile(ed.Pic2);
            DeleteFile(ed.Pic3);
            DeleteFile(ed.Pic4);
            eventReposity.DeleteEventDailyRecord(ed);

            return RedirectToAction("Track", new { eventId = eventId });
        }

        public ActionResult AddDailyRecord(long eventId)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;

            
            EventRecord e = eventReposity.GetEventRecordById(eventId);
            EventRecordDetail detail = eventReposity.GetEventDetail(e);
            int progress = eventReposity.GetCurrentProgress(eventId);
            EventDailyRecord ed = new EventDailyRecord();
            ed.EventId = eventId;
            ed.CreatedDate = DateTime.Now;
            ed.OccurredDate = DateTime.Now;
            ed.Status = 0;
            ed.Progress = progress;

            ViewData["dailyRecord"] = ed;

            return View("EditDailyRecord", detail);
        }

        [HttpPost]
        public ActionResult AddDailyRecord(FormCollection form)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Auditor);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            ViewData["types"] = types;
            ViewData["priorites"] = priorities;


            string eventDesc = form.Get("EventDesc");
            int status = parseInt(form.Get("status"));
            int progress = parseInt(form.Get("progress"));
            int eventId = parseInt(form.Get("eventId"));
            DateTime occurredDate = DateTime.Parse(form.Get("occurredDate"));

            EventRecord e = eventReposity.GetEventRecordById(eventId);
            EventDailyRecord ed = new EventDailyRecord();
            ed.EventId = eventId;
            ed.OccurredDate = occurredDate;
            ed.Progress = progress;
            ed.Status = status + 1;
            ed.CreatedDate = DateTime.Now;
            ed.RecorderId = GetCurrentUser().Id;
            ed.Description = eventDesc;
            StoreImages(form, e, ed);

            eventReposity.CreateEventDailyRecord(ed);

            EventRecordDetail detail = eventReposity.GetEventDetail(e);
            e.Progress = progress;
            if (status > 0)
            {
                e.Status = status;
            }
            eventReposity.UpdateEventRecord(e);

            ViewData["dailyRecord"] = ed;

            return RedirectToAction("Track", new { eventId = ed.EventId });
        }

        public ActionResult Create()
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;

            long factoryId = 0;
            if (user.RoleId != (int)RoleEnum.Expert)
            {
                factoryId = user.FactoryId;
            }

            ShowFactoryList(factoryId);
            ShowStackAndTailingoind(factoryId, 0);
            EventRecord e = new EventRecord();
            e.FactoryID = factoryId;
            e.CreateDate = DateTime.Now;
            e.OccurredDate = DateTime.Now;

            ViewData["dailyRecord"] = new EventDailyRecord();
            ViewData["showFactory"] = user.RoleId == (int)RoleEnum.Expert;

            return View(e);
        }

        [HttpPost]
        public ActionResult Create(EventRecord e, FormCollection form)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;

            e.CreateDate = DateTime.Now;
            e.Progress = 0;
            e.Status = 0;
            e.RecorderId = user.Id;
            int stackType = 0, stackId = 0;
            ParseSid(form.Get("stackId"), ref stackId, ref stackType);
            e.Stack_Id = stackId;
            e.StackType = stackType;


            eventReposity.CreateEventRecord(e);

            string eventDesc = form.Get("EventDesc");

            EventDailyRecord ed = new EventDailyRecord();
            ed.CreatedDate = DateTime.Now;
            ed.OccurredDate = e.OccurredDate;
            ed.RecorderId = GetCurrentUser().Id;
            ed.Progress = 0;
            ed.Status = 1;
            ed.EventId = e.Id;
            ed.Description = eventDesc;
            StoreImages(form, e, ed);

            eventReposity.CreateEventDailyRecord(ed);

            ViewData["dailyRecord"] = ed;
            ViewData["showFactory"] = user.RoleId == (int)RoleEnum.Expert;

            ShowFactoryList(e.FactoryID);
            ShowStackAndTailingoind(e.FactoryID, 0, stackId, stackType);

            return RedirectToAction("List", new { status = 0 });
        }

        public ActionResult Edit(long eventId)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            ViewData["showFactory"] = user.RoleId == (int)RoleEnum.Expert;
            
            EventRecord e = eventReposity.GetEventRecordById(eventId);
            EventDailyRecord ed = eventReposity.GetEventDailyRecordByEventId(eventId);

            ShowFactoryList(e.FactoryID);
            ShowStackAndTailingoind(e.FactoryID, 0, (int)e.Stack_Id, e.StackType);
            ViewData["dailyrecord"] = ed;

            return View("Create", e);
        }

        [HttpPost]
        public ActionResult Edit(EventRecord e, FormCollection form)
        {
            List<RoleEnum> roles = new List<RoleEnum>();
            roles.Add(RoleEnum.Recorder);
            roles.Add(RoleEnum.Expert);
            ActionResult result = AllowForRole(roles);
            if (result != null)
            {
                return result;
            }
            User user = GetCurrentUser();
            ViewData["user"] = user;
            ViewData["showFactory"] = user.RoleId == (int)RoleEnum.Expert;

            EventRecord oldEvent = eventReposity.GetEventRecordById(e.Id);
            int stackType = 0, stackId = 0;
            ParseSid(form.Get("stackId"), ref stackId, ref stackType);
            oldEvent.FactoryID = e.FactoryID;
            oldEvent.Stack_Id = stackId;
            oldEvent.StackType = stackType;
            oldEvent.Name = e.Name;
            oldEvent.OccurredDate = e.OccurredDate;
            oldEvent.Priority = e.Priority;
            oldEvent.Type = e.Type;
            eventReposity.UpdateEventRecord(oldEvent);

            string eventDesc = form.Get("EventDesc");

            EventDailyRecord ed = eventReposity.GetEventDailyRecordByEventId(e.Id);
            ed.OccurredDate = e.OccurredDate;
            ed.RecorderId = GetCurrentUser().Id;
            ed.Description = eventDesc;
            StoreImages(form, oldEvent, ed);

            eventReposity.UpdateEventDailyRecord(ed);

            ShowFactoryList(e.FactoryID);
            ShowStackAndTailingoind(e.FactoryID, 0, stackId, stackType);
            ViewData["dailyrecord"] = ed;

            return RedirectToAction("List", new { status = 0 });
        }

        private void StoreImages(FormCollection form, EventRecord e, EventDailyRecord ed)
        {
            string picPath1 = form.Get("picPath1");
            string picDes1 = form.Get("picDes1");
            string picPath2 = form.Get("picPath2");
            string picDes2 = form.Get("picDes2");
            string picPath3 = form.Get("picPath3");
            string picDes3 = form.Get("picDes3");
            string picPath4 = form.Get("picPath4");
            string picDes4 = form.Get("picDes4");

            ed.PicNum = 0;
            string oldPicPath = string.Empty;

            if (!string.IsNullOrEmpty(picPath1))
            {
                oldPicPath = ed.Pic1;
                ed.Pic1 = picPath1;
                ed.Pic1_desc = picDes1;
                ed.PicNum = ed.PicNum + 1;
                ed.Pic1 = MoveImage(e, ed, ed.Pic1, 1, oldPicPath);
            }
            else
            {
                ed.Pic1 = null;
                ed.Pic1_desc = null;
            }

            if (!string.IsNullOrEmpty(picPath2))
            {
                oldPicPath = ed.Pic2;
                ed.Pic2 = picPath2;
                ed.Pic2_desc = picDes2;
                ed.PicNum = ed.PicNum + 1;
                ed.Pic2 = MoveImage(e, ed, ed.Pic2, 2, oldPicPath);
            }
            else
            {
                ed.Pic2 = null;
                ed.Pic2_desc = null;
            }

            if (!string.IsNullOrEmpty(picPath3))
            {
                oldPicPath = ed.Pic3;
                ed.Pic3 = picPath3;
                ed.Pic3_desc = picDes3;
                ed.PicNum = ed.PicNum + 1;
                ed.Pic3 = MoveImage(e, ed, ed.Pic3, 3, oldPicPath);
            }
            else
            {
                ed.Pic3 = null;
                ed.Pic3_desc = null;
            }

            if (!string.IsNullOrEmpty(picPath4))
            {
                oldPicPath = ed.Pic4;
                ed.Pic4 = picPath4;
                ed.Pic4_desc = picDes4;
                ed.PicNum = ed.PicNum + 1;
                ed.Pic4 = MoveImage(e, ed, ed.Pic4, 4, oldPicPath);
            }
            else
            {
                ed.Pic4 = null;
                ed.Pic4_desc = null;
            }
        }

        private string MoveImage(EventRecord e, EventDailyRecord ed, string path, int index, string oldPicPath)
        {
            string fileName = !path.StartsWith("~") ? ("~" + path) : path;
            long tick = DateTime.Now.Ticks; 
            Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32)); 
            if (fileName.StartsWith("~/Upload/Images/"))
            {
                int days = (ed.OccurredDate.Date - e.OccurredDate.Date).Days;
                string stackFolder = e.FactoryID.ToString("00") + e.Stack_Id.ToString("00") + (e.StackType == 0 ? "dc" : "wk");
                string dateFolder = e.OccurredDate.ToString("yyyyMMdd") + "_" + e.Id.ToString("00");
                string filePath = "~/Upload/Events/" + stackFolder + "/" + dateFolder + "/";
                string fullPath = Server.MapPath(filePath);
                fileName = filePath + days.ToString("000") + "_" + index + "_" + ran.Next(1000) + ".jpg";
                path = Server.MapPath("~" + path);
                string fullFileName = Server.MapPath(fileName);
                if (!Directory.Exists(fullPath))
                {
                    Directory.CreateDirectory(fullPath);
                }
                System.IO.File.Copy(path, fullFileName, true);
                System.IO.File.Delete(path);
                if (!string.IsNullOrEmpty(oldPicPath) && System.IO.File.Exists(Server.MapPath(oldPicPath)))
                {
                    System.IO.File.Delete(Server.MapPath(oldPicPath));
                }
            }
            return fileName;
        }

        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileWrapper file)
        {
            string error = "";
            string url = "";
            if (file != null)
            {
                /*
                if (!string.Equals("image/jpeg", file.ContentType, StringComparison.CurrentCultureIgnoreCase) && !string.Equals("image/pjpeg", file.ContentType, StringComparison.CurrentCultureIgnoreCase))
                {
                    error = "只能上传jpeg格式图片.";
                }
                else 
                */
                if (file.ContentLength > 200 * 1024)
                {
                    error = "文件太大，必须小于200KB.";
                }
                else
                {
                    url = UploadFile(file, FileType.Image);
                }
            }
            ViewData["error"] = error;
            ViewData["url"] = url;

            return View();
        }

        [HttpPost]
        public ActionResult DelFile(string file)
        {
            string error = DeleteFile(file);
            string url = "~/";
            

            ViewData["error"] = error;
            ViewData["url"] = url;

            return View("FileUpload");
        }

        private string DeleteFile(string file)
        {
            string error = "";
            try
            {
                if (file != null && (file.StartsWith("/Upload/") || file.StartsWith("~/Upload/")))
                {
                    if (!file.StartsWith("~"))
                    {
                        file = "~" + file;
                    }
                    string path = Server.MapPath(file);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);
                    }
                }
            }
            catch (Exception e)
            {
                error = e.Message;
            }

            return error;
        }
    }
}
